package com.gitee.feizns.explore.data_structure.linked_list.singly.reverseKGroup;

import com.gitee.feizns.explore.data_structure.linked_list.singly.ListNode;

/**
 * @author feizns
 * @since 2020/3/9
 */
public class ReverseKGroup {

    public static void main(String[] args) {
//        reverseKGroup(create(), 2).print();
    }

//    private static ListNode create() {
//        ListNode ret = new ListNode(0);
//        ret.next = new ListNode(1);
//        ret.next.next = new ListNode(2);
//        ret.next.next.next = new ListNode(3);
//        ret.next.next.next.next = new ListNode(4);
//        ret.next.next.next.next.next = new ListNode(5);
//        return ret;
//    }

    public static ListNode reverseKGroup(ListNode head, int k) {
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode start = pre;
        ListNode curt = pre;
        while ( start.next != null ) {
            for (int i = 0; i < k && curt != null; i++)
                curt = curt.next;
            if ( curt == null )
                break;
            ListNode next = curt.next;
            curt.next = null;
            ListNode reverse = reverse(start.next);
            start.next.next = next;
            ListNode nextS = start.next;
            start.next = reverse;
            start = nextS;
            curt = start;
        }
        return pre.next;
    }

    private static ListNode reverse(ListNode head) {
        if ( head != null && head.next != null ) {
            ListNode ret = reverse(head.next);
            head.next.next = head;
            head.next = null;
            return ret;
        }
        return head;
    }

}
